package com.sudoku.sound;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.audio.Sound;
import com.sudoku.observer.Event;
import com.sudoku.observer.Observer;
import com.sudoku.observer.Subject;
import com.sudoku.utility.Constants;
import com.sudoku.utility.Locator;

public class AudioManager implements Constants, Observer {

	public float SWITCH_MUSIC_TIME = 2;
	public float DEFAULT_VOLUME = 0.5f;

	private float musicVolume;
	private float effectsVolume;
	private float previousMusicVolume;
	private float previousEffectsVolume;
	private IAudio audio;

	private Map<String, Sound> soundList;

	public AudioManager(IAudio audio, boolean mute, Subject subject) {
		this.audio = audio;
		musicVolume = previousMusicVolume = DEFAULT_VOLUME;
		effectsVolume = previousEffectsVolume = DEFAULT_VOLUME;
		subject.addObserver(this);

		if (mute) {
			mute();
		}

		initSounds();
	}

	public void mute() {
		Locator.setMute(true);
		effectsVolume = 0;
		musicVolume = 0;
		audio.setMusicVolume(musicVolume);
	}

	public void unmute() {
		Locator.setMute(false);
		musicVolume = previousMusicVolume;
		effectsVolume = previousEffectsVolume;
		audio.setMusicVolume(musicVolume);
	}
	
	public void flipMute() {
		if(Locator.isMute()){
			unmute();
		} else {
			mute();
		}
		
	}

	@Override
	public void onNotify(Event event) {
		switch (event) {
		case EVENT_CLICK:
			audio.playSound(soundList.get(MENU_CLICK), effectsVolume);
			break;
		case EVENT_SELECT_TILE:
			audio.playSound(soundList.get(SELECT_TILE), effectsVolume);
			break;
		case EVENT_BUTTON_CLICK:
            audio.playSound(soundList.get(BUTTON_CLICK), effectsVolume);
            break;
		case EVENT_WIN_PUZZLE:
            audio.playSound(soundList.get(WIN_PUZZLE), effectsVolume);
            break;
		case EVENT_LOSE_PUZZLE:
            audio.playSound(soundList.get(LOSE_PUZZLE), effectsVolume);
            break;
		default:
			break;
		}
	}

	private void initSounds() {
		soundList = new HashMap<String, Sound>();
		soundList.put(MENU_CLICK, Locator.getAssets().get(MENU_CLICK, Sound.class));
		soundList.put(SELECT_TILE, Locator.getAssets().get(SELECT_TILE, Sound.class));
		soundList.put(BUTTON_CLICK, Locator.getAssets().get(BUTTON_CLICK, Sound.class));
		soundList.put(WIN_PUZZLE, Locator.getAssets().get(WIN_PUZZLE, Sound.class));
		soundList.put(LOSE_PUZZLE, Locator.getAssets().get(LOSE_PUZZLE, Sound.class));
	}

}
